package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/category")
public class CategoryController {
    //注入service对象
    @Autowired
    private CategoryService categoryService;

    //新增分类
    @PostMapping
    public R save(HttpSession session, @RequestBody Category category) {
        log.info("传递参数：{}", category);
        //    获取登录人id
        Long employee = (Long) session.getAttribute("loginEmployee");
        log.info("登录人id：{}", employee);
     /*   //    设置公共字段
        category.setCreateTime(LocalDateTime.now());
        category.setUpdateTime(LocalDateTime.now());
        category.setCreateUser(employee);
        category.setUpdateUser(employee);*/
        //    新增
        boolean save = categoryService.save(category);
        if (!save) {
            return R.error("新增失败");
        }
        ;
        return R.success("新增成功");

    }

    //分类分页查询
    @GetMapping("/page")
    public R page(int page, int pageSize) {
        //分页查询
        Page page1 = new Page(page, pageSize);
        //    过滤条件
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        lqw.orderByAsc(Category::getSort);
        //查询
        categoryService.page(page1, lqw);
        return R.success(page1);
    }

    //菜品套餐删除
    @DeleteMapping
    public R deleteById(Long id) {
        log.info("删除分类，id为：{}", id);
//        调用service删除操作
        categoryService.deleteById(id);
        return R.success("分类信息删除成功");
    }

    //    修改分类
    @PutMapping
    public R put(HttpSession session, @RequestBody Category category) {
     /*   //    设置公共字段
        Long loginEmployeeId = (Long) session.getAttribute("loginEmployee");
        category.setUpdateTime(LocalDateTime.now());
        category.setUpdateUser(loginEmployeeId);
*/
        boolean b = categoryService.updateById(category);
        if (!b) {
            return R.error("修改失败");
        }

        return R.success("修改成功");
    }

    //    询菜品分类列表数据
    @GetMapping("/list")
    public R list(Category category) {
        //条件构造器
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        //    添加条件
        if(category.getType()!= null){
            lqw.eq(Category::getType, category.getType());
        }
        //添加排序
        lqw.orderByAsc(Category::getSort).orderByAsc(Category::getUpdateTime);
        List<Category> list = categoryService.list(lqw);
        return R.success(list);

    }





}
